<template>
  <view class="detail-container">
    <!-- 商品轮播图 -->
    <swiper class="product-swiper" circular autoplay interval="3000" duration="500" indicator-dots>
      <swiper-item v-for="(image, index) in product.images" :key="index">
        <image :src="image" mode="aspectFill"></image>
      </swiper-item>
    </swiper>

    <!-- 悬浮按钮组 -->
    <view class="float-buttons">
      <view class="float-btn back" @tap="goBack">
        <uni-icons type="left" size="20" color="#fff"></uni-icons>
      </view>
      <view class="float-btn share" @tap="handleShare">
        <uni-icons type="redo" size="20" color="#fff"></uni-icons>
      </view>
    </view>

    <!-- 商品信息 -->
    <view class="product-info">
      <view class="price-section">
        <text class="price">¥{{ product.price }}</text>
        <text class="original-price" v-if="product.originalPrice">¥{{ product.originalPrice }}</text>
      </view>
      <view class="title-section">
        <text class="title">{{ product.name }}</text>
        <view class="share-btn" @click="handleShare">
          <uni-icons :type="mapUviewIconName('share')" size="40" color="#666"></uni-icons>
          <text>分享</text>
        </view>
      </view>
      <view class="desc">{{ product.description }}</view>
      <view class="sales-info">
        <text>销量 {{ product.sales }}</text>
        <text>库存 {{ product.stock }}</text>
      </view>
    </view>

    <!-- 规格选择 -->
    <view class="specs-section" @click="openSpecsPopup">
      <text class="label">规格</text>
      <view class="content">
        <text :class="{'spec-placeholder': !selectedSpecs}">{{ selectedSpecs || '请选择规格' }}</text>
        <uni-icons :type="mapUviewIconName('arrow-right')" size="24" color="#999"></uni-icons>
      </view>
    </view>

    <!-- 商品详情 -->
    <view class="detail-section">
      <view class="section-title">商品详情</view>
      <rich-text :nodes="product.detail"></rich-text>
    </view>

    <!-- 评论列表 -->
    <view class="comments-section">
      <view class="section-header">
        <view class="title">
          <text class="main">商品评论</text>
          <text class="count">({{ commentStats.total || 0 }})</text>
        </view>
        <view class="stats">
          <text>好评率 {{ commentStats.goodRate }}%</text>
          <view class="filter-btn">
            最新 <uni-icons type="down" size="12" color="#666"></uni-icons>
          </view>
        </view>
      </view>
      
      <!-- 评论列表 -->
      <view class="comment-list" v-if="comments.list.length > 0">
        <view 
          class="comment-item" 
          v-for="comment in comments.list" 
          :key="comment.id"
          @tap="showCommentDetail(comment.id)"
        >
          <view class="user-info">
            <view class="left">
              <image class="avatar" :src="comment.avatar || '/static/images/default-avatar.png'" mode="aspectFill"></image>
              <view class="user-meta">
                <text class="nickname">{{ comment.nickname || '匿名用户' }}</text>
                <view class="purchase-info" v-if="comment.isAnonymous">本店买过2次</view>
              </view>
            </view>
            <text class="time">{{ formatCommentTime(comment.createTime) }}</text>
          </view>
          <view class="rating">
            <uni-rate :value="comment.rating" size="18" disabled color="#ff5500"></uni-rate>
          </view>
          <view class="comment-content">{{ comment.content }}</view>
          <view class="comment-images" v-if="comment.images && comment.images.length > 0">
            <image 
              v-for="(image, index) in comment.images" 
              :key="index" 
              :src="image" 
              mode="aspectFill"
              @tap.stop="previewImage(comment.images, index)"
            ></image>
          </view>
          <view class="comment-footer">
            <view class="actions">
              <view class="action-btn" @tap.stop="toggleCommentLike(comment)">
                <uni-icons :type="comment.isLiked ? 'heart-filled' : 'heart'" size="24" :color="comment.isLiked ? '#ff5500' : '#999'"></uni-icons>
                <text>{{ comment.likeCount || 0 }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-comments" v-else>
        <text>暂无评论</text>
      </view>
      
      <!-- 加载更多 -->
      <uni-load-more :status="commentsLoadMoreStatus" v-if="comments.list.length > 0"></uni-load-more>
    </view>

    <!-- 评论详情弹窗 -->
    <uni-popup ref="commentDetailPopup" type="center">
      <view class="comment-detail-popup">
        <view class="popup-header">
          <text class="title">评论详情</text>
          <view class="close-btn" @tap="closeCommentDetailPopup">
            <uni-icons type="close" size="24" color="#999"></uni-icons>
          </view>
        </view>
        <scroll-view scroll-y class="popup-content">
          <view class="user-info" v-if="currentComment">
            <image class="avatar" :src="currentComment.avatar" mode="aspectFill"></image>
            <view class="user-meta">
              <text class="nickname">{{ currentComment.nickname }}</text>
              <text class="time">{{ formatCommentTime(currentComment.createTime) }}</text>
            </view>
          </view>
          <view class="comment-content" v-if="currentComment">
            <text>{{ currentComment.content }}</text>
            <view class="comment-images" v-if="currentComment.images && currentComment.images.length > 0">
              <image 
                v-for="(image, index) in currentComment.images" 
                :key="index" 
                :src="image" 
                mode="aspectFill"
                @tap="previewImage(currentComment.images, index)"
              ></image>
            </view>
          </view>
        </scroll-view>
      </view>
    </uni-popup>

    <!-- 底部操作栏 -->
    <view class="bottom-bar">
      <view class="left-btns">
        <view class="btn-item" @click="toMerchantDetail">
          <uni-icons :type="mapUviewIconName('shop')" size="32" color="#666"></uni-icons>
          <text>商家</text>
        </view>
        <view class="btn-item" @click="toggleFavorite">
          <uni-icons :type="mapUviewIconName(isFavorite ? 'star-fill' : 'star')" size="32" :color="isFavorite ? '#ff5500' : '#666'"></uni-icons>
          <text>收藏</text>
        </view>
        <view class="btn-item" @click="toCart">
          <uni-icons :type="mapUviewIconName('shopping-cart')" size="32" color="#666"></uni-icons>
          <text>购物车</text>
          <view class="cart-badge" v-if="cartCount > 0">{{ cartCount > 99 ? '99+' : cartCount }}</view>
        </view>
      </view>
      <view class="right-btns">
        <button class="add-cart-btn" @click="handleAddToCart">加入购物车</button>
        <button class="buy-btn" @click="handleBuyNow">立即购买</button>
      </view>
    </view>

    <!-- 规格选择弹窗 -->
    <uni-popup ref="specsPopup" type="bottom" :mask-click="true" @change="onSpecsPopupChange">
      <view class="specs-popup">
        <view class="popup-header">
          <image :src="product.mainImage" mode="aspectFill" class="product-image"></image>
          <view class="selected-info">
            <text class="price">¥{{ selectedPrice }}</text>
            <text class="stock">库存: {{ selectedStock }}</text>
            <text class="selected">已选: {{ selectedSpecs || '请选择规格' }}</text>
          </view>
          <view class="close-btn" @click="closeSpecsPopup">
            <uni-icons :type="mapUviewIconName('close')" size="24" color="#999"></uni-icons>
          </view>
        </view>
        <scroll-view scroll-y class="specs-content">
          <view v-if="specsList && specsList.length > 0">
            <view v-for="(spec, index) in specsList" :key="index" class="spec-group">
              <text class="spec-title">{{ spec.name }}</text>
              <view class="spec-items">
                <text 
                  v-for="(item, idx) in spec.values" 
                  :key="idx"
                  :class="['spec-item', { active: isSpecSelected(spec.name, item) }]"
                  @click="selectSpec(spec.name, item)"
                >{{ item }}</text>
              </view>
            </view>
          </view>
          <view v-else class="no-specs-tip">
            <text>此商品无规格选项</text>
          </view>
          <view class="quantity-section">
            <text class="quantity-label">数量</text>
            <uni-number-box v-model="quantity" :min="1" :max="selectedStock"></uni-number-box>
          </view>
        </scroll-view>
        <view class="popup-footer">
          <button class="confirm-btn" @click="confirmSpecs">确定</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { checkLogin } from '@/utils/auth'
import { mapUviewIconName } from '@/utils/icon-mapper.js'
import { formatDate } from '@/utils/date'
import api from '@/config/api'

export default {
  data() {
    return {
      id: null,
      pageEnterTime: 0,
      product: {
        id: null,
        name: '',
        description: '',
        image: '',
        images: [],
        price: 0,
        originalPrice: 0,
        stock: 0,
        sales: 0,
        status: 1,
        favorite: false,
        favoriteTime: null,
        detail: '',
        specs: [],
        merchantId: null
      },
      showSpecsPopup: false,
      selectedSpecs: '',
      selectedPrice: 0,
      selectedStock: 0,
      quantity: 1,
      isFavorite: false,
      selectedSpecsObj: {},
      cartCount: 0,
      specsList: [],
      skuList: [],
      selectedSku: null,
      comments: {
        list: [],
        pageNum: 1,
        pageSize: 10,
        hasMore: true
      },
      commentStats: {
        total: 0,
        goodRate: 0
      },
      commentsLoadMoreStatus: 'more',
      currentComment: null
    }
  },
  computed: {
    hasSpecs() {
      return Array.isArray(this.specsList) && 
             this.specsList.length > 0 && 
             this.specsList.some(spec => spec.values && Array.isArray(spec.values) && spec.values.length > 0);
    }
  },
  onLoad(options) {
    console.log('商品详情页 onLoad, options:', options)
    if (!options || !options.id) {
      console.error('缺少商品ID参数')
      uni.showToast({
        title: '参数错误',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
      return
    }
    
    this.id = options.id
    console.log('开始加载商品详情, ID:', this.id)
    this.loadProductDetail()
    this.loadComments()
  },
  onShow() {
    this.pageEnterTime = Date.now()
    this.loadCartCount()
  },
  onHide() {
    this.recordBrowsingHistory()
  },
  onUnload() {
    this.recordBrowsingHistory()
  },
  methods: {
    mapUviewIconName,
    formatDate,
    async loadProductDetail() {
      try {
        console.log('加载商品详情, ID:', this.id)
        
        uni.showLoading({
          title: '加载中...',
          mask: true
        })
        
        const [detailRes, specsRes, skusRes] = await Promise.all([
          api.product.base.detail(this.id),
          api.product.specs.getSpecs(this.id),
          api.product.specs.getSkus(this.id)
        ])
        
        uni.hideLoading()
        
        if (detailRes && detailRes.data) {
          // 处理商品数据
          const productData = detailRes.data
          
          // 处理图片数组
          let images = []
          
          // 添加主图
          if (productData.mainImage) {
            images.push(productData.mainImage)
          }
          
          // 处理子图
          if (productData.subImages) {
            let subImages = []
            if (Array.isArray(productData.subImages)) {
              subImages = productData.subImages
            } else if (typeof productData.subImages === 'string') {
              subImages = productData.subImages.split(',').filter(img => img.trim())
            }
            // 确保子图不重复添加主图
            subImages = subImages.filter(img => img !== productData.mainImage)
            images = [...images, ...subImages]
          }
          
          // 如果没有任何图片，使用默认图片
          if (images.length === 0) {
            images = ['/static/images/product-placeholder.png']
          }
          
          // 更新商品数据
          this.product = {
            ...this.product,
            ...productData,
            images: images
          }

          // 更新规格和 SKU 数据
          if (specsRes && specsRes.data) {
            this.specsList = specsRes.data
          }
          
          if (skusRes && skusRes.data) {
            this.skuList = skusRes.data
          }
          
          // 设置默认价格和库存
          this.selectedPrice = this.product.price
          this.selectedStock = this.product.stock
          
          // 初始化规格选择
          if (this.specsList.length > 0) {
            this.selectedSpecsObj = this.specsList.reduce((acc, spec) => {
              acc[spec.name] = ''
              return acc
            }, {})
          }
          
          console.log('处理后的商品数据:', this.product)
          
          // 记录浏览历史
          this.recordBrowsingHistory()
        } else {
          this.handleLoadError(detailRes?.message || '商品不存在')
        }
      } catch (error) {
        uni.hideLoading()
        console.error('加载商品详情失败:', error)
        this.handleLoadError('加载失败，请重试')
      }
    },
    
    // 处理加载错误
    handleLoadError(message) {
      uni.showToast({
        title: message,
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    },
    
    // 检查收藏状态
    async checkFavoriteStatus() {
      try {
        if (checkLogin(false)) {
          const res = await api.product.favorite.checkFavorite(this.id)
          this.isFavorite = res?.data === true
        }
      } catch (error) {
        console.error('检查收藏状态失败:', error)
      }
    },
    
    // 切换收藏状态
    async toggleFavorite() {
      if (!checkLogin()) return
      
      try {
        if (this.isFavorite) {
          await api.product.favorite.cancel(this.id)
          this.isFavorite = false
          uni.showToast({
            title: '已取消收藏',
            icon: 'success'
          })
        } else {
          await api.product.favorite.add(this.id)
          this.isFavorite = true
          uni.showToast({
            title: '已收藏',
            icon: 'success'
          })
        }
      } catch (error) {
        console.error('收藏操作失败:', error)
        uni.showToast({
          title: '操作失败',
          icon: 'none'
        })
      }
    },
    
    // 记录浏览历史
    async recordBrowsingHistory() {
      if (!this.pageEnterTime || !this.id) return
      
      try {
        const stayDuration = Math.floor((Date.now() - this.pageEnterTime) / 1000)
        if (stayDuration > 0) {
          await api.user.history.add(this.id, {
            stayDuration: stayDuration,
            categoryId: this.product.categoryId
          })
          // 重置进入时间，防止重复记录
          this.pageEnterTime = 0
        }
      } catch (error) {
        console.error('记录浏览历史失败:', error)
      }
    },
    openSpecsPopup() {
      this.$refs.specsPopup.open()
    },
    closeSpecsPopup() {
      this.$refs.specsPopup.close()
    },
    onSpecsPopupChange(e) {
      this.showSpecsPopup = e.show
    },
    isSpecSelected(name, value) {
      return this.selectedSpecsObj[name] === value
    },
    selectSpec(name, value) {
      this.selectedSpecsObj[name] = value
      this.updateSelectedSpecs()
      this.updateSelectedSku()
    },
    updateSelectedSpecs() {
      const specs = []
      for (const [name, value] of Object.entries(this.selectedSpecsObj)) {
        if (value) {
          specs.push(`${name}:${value}`)
        }
      }
      this.selectedSpecs = specs.join('; ')
    },
    updateSelectedSku() {
      // 检查是否所有规格都已选择
      const isAllSelected = Object.values(this.selectedSpecsObj).every(value => value !== '')
      
      if (!isAllSelected) {
        this.selectedSku = null
        this.selectedPrice = this.product.price
        this.selectedStock = this.product.stock
        return
      }

      // 查找匹配的SKU
      this.selectedSku = this.skuList.find(sku => {
        return Object.entries(this.selectedSpecsObj).every(([name, value]) => 
          sku.specs[name] === value
        )
      })

      if (this.selectedSku) {
        this.selectedPrice = this.selectedSku.price
        this.selectedStock = this.selectedSku.stock
      }
    },
    confirmSpecs() {
      if (this.hasSpecs && !this.selectedSku) {
        uni.showToast({
          title: '请选择规格',
          icon: 'none'
        })
        return
      }
      this.closeSpecsPopup()
    },
    async handleAddToCart() {
      // 检查登录状态
      if (!checkLogin()) {
        // 保存当前页面路径
        const pages = getCurrentPages()
        const currentPage = pages[pages.length - 1]
        if (currentPage && currentPage.route) {
          uni.setStorageSync('loginRedirect', `/${currentPage.route}`)
        }
        
        // 使用uni.navigateTo的完整回调形式
        try {
          await new Promise((resolve, reject) => {
            uni.navigateTo({
              url: '/pages/user/auth/login',
              success: resolve,
              fail: reject
            })
          })
        } catch (error) {
          console.error('跳转登录页失败:', error)
          return
        }
        return
      }
      
      if (this.hasSpecs && !this.selectedSku) {
        this.openSpecsPopup()
        return
      }

      try {
        uni.showLoading({ title: '添加中...' })
        
        // 构造符合API要求的数据对象
        const data = {
          productId: this.id,
          quantity: this.quantity,
          skuId: this.selectedSku?.id || undefined // 如果没有选择SKU，则不传此参数
        }
        
        console.log('添加购物车数据:', data)
        const res = await this.$api.cart.add(data)
        
        uni.hideLoading()
        if (res.code === 200) {
          this.loadCartCount()
          
          uni.showToast({
            title: '添加成功',
            icon: 'success'
          })
          this.closeSpecsPopup()
        } else {
          uni.showToast({
            title: res.message || '添加失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        console.error('添加购物车失败:', error)
        uni.showToast({
          title: '添加失败',
          icon: 'none'
        })
      }
    },
    handleBuyNow() {
      if (!checkLogin()) return
      
      if (this.hasSpecs && !this.selectedSku) {
        this.openSpecsPopup()
        return
      }

      const orderData = {
        productId: this.id,
        quantity: this.quantity,
        skuId: this.selectedSku?.id
      }

      uni.navigateTo({
        url: `/pages/order/confirm/index?data=${encodeURIComponent(JSON.stringify(orderData))}`
      })
    },
    toMerchantDetail() {
      if (!this.product.merchantId) return
      
      uni.navigateTo({
        url: `/pages/shop/detail/index?id=${this.product.merchantId}`
      })
    },
    toCart() {
      if (!checkLogin()) return
      
      uni.showLoading({
        title: '正在跳转...',
        mask: true
      })
      
      setTimeout(() => {
        uni.hideLoading()
        uni.switchTab({
          url: '/pages/cart/index'
        })
      }, 300)
    },
    handleShare() {
      // TODO: 实现分享功能
    },
    async loadCartCount() {
      try {
        if (api && api.cart && typeof api.cart.count === 'function') {
          const res = await api.cart.count()
          if (res && res.data) {
            this.cartCount = res.data
          }
        }
      } catch (error) {
        console.error('获取购物车数量失败:', error)
      }
    },
    // 格式化评论时间
    formatCommentTime(time) {
      if (!time) return ''
      
      // 处理数组格式的时间
      if (Array.isArray(time)) {
        // 确保数组长度足够
        if (time.length >= 6) {
          const [year, month, day, hour, minute] = time
          // 补零函数
          const pad = (num) => String(num).padStart(2, '0')
          return `${year}-${pad(month)}-${pad(day)} ${pad(hour)}:${pad(minute)}`
        }
        return ''
      }
      
      // 如果是字符串格式，直接返回
      return time
    },
    // 加载评论列表
    async loadComments(isLoadMore = false) {
      if (!isLoadMore) {
        this.comments.pageNum = 1
        this.comments.list = []
        this.comments.hasMore = true
      }

      if (!this.comments.hasMore) {
        this.commentsLoadMoreStatus = 'noMore'
        return
      }

      try {
        this.commentsLoadMoreStatus = 'loading'
        const res = await this.$api.product.comment.getProductComments(this.id, {
          pageNum: this.comments.pageNum,
          pageSize: this.comments.pageSize
        })

        if (res.code === 200 && res.data) {
          const { records, total } = res.data
          
          // 处理评论数据
          const processedRecords = records.map(comment => ({
            id: comment.id,
            productId: comment.productId,
            userId: comment.userId,
            nickname: comment.nickname || '匿名用户',
            avatar: comment.avatar || '/static/images/default-avatar.png',
            rating: comment.rating || 5,
            content: comment.content || '',
            images: comment.images || [], // 直接使用返回的图片数组
            reply: comment.reply,
            replyTime: comment.replyTime,
            likeCount: comment.likeCount || 0,
            isLiked: comment.isLiked || false,
            isAnonymous: comment.isAnonymous || false,
            createTime: comment.createTime
          }))
          
          // 更新评论列表
          if (isLoadMore) {
            this.comments.list = [...this.comments.list, ...processedRecords]
          } else {
            this.comments.list = processedRecords
          }

          // 更新评论统计
          this.commentStats.total = total
          if (total > 0) {
            // 计算好评率（这里假设评分>=4为好评）
            const goodComments = processedRecords.filter(comment => comment.rating >= 4).length
            this.commentStats.goodRate = Math.round((goodComments / processedRecords.length) * 100)
          }

          // 更新加载状态
          this.comments.hasMore = this.comments.list.length < total
          this.commentsLoadMoreStatus = this.comments.hasMore ? 'more' : 'noMore'
        }
      } catch (error) {
        console.error('加载评论失败:', error)
        this.commentsLoadMoreStatus = 'more'
        uni.showToast({
          title: '加载评论失败',
          icon: 'none'
        })
      }
    },
    // 显示评论详情
    async showCommentDetail(commentId) {
      try {
        // 获取评论详情
        const res = await this.$api.user.comment.getDetail(commentId)
        
        if (res.code === 200 && res.data) {
          this.currentComment = {
            ...res.data,
            avatar: res.data.avatar || '/static/images/default-avatar.png',
            nickname: res.data.nickname || '匿名用户'
          }
          this.$refs.commentDetailPopup.open()
        } else {
          uni.showToast({
            title: '获取评论详情失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取评论详情失败:', error)
        uni.showToast({
          title: '获取评论详情失败',
          icon: 'none'
        })
      }
    },
    // 关闭评论详情弹窗
    closeCommentDetailPopup() {
      this.$refs.commentDetailPopup.close()
      this.currentComment = null
    },
    // 预览图片
    previewImage(images, current) {
      uni.previewImage({
        urls: images,
        current: images[current]
      })
    },
    // 点赞评论
    async toggleCommentLike(comment) {
      if (!checkLogin()) {
        uni.navigateTo({
          url: '/pages/user/auth/login'
        })
        return
      }

      try {
        // 乐观更新UI
        comment.isLiked = !comment.isLiked
        comment.likeCount = comment.likeCount + (comment.isLiked ? 1 : -1)

        // TODO: 调用点赞API
        // const res = await this.$api.product.comment.toggleLike(comment.id)
        
      } catch (error) {
        // 恢复之前的状态
        comment.isLiked = !comment.isLiked
        comment.likeCount = comment.likeCount + (comment.isLiked ? 1 : -1)
        
        uni.showToast({
          title: '操作失败',
          icon: 'none'
        })
      }
    },
    // 加载更多评论
    loadMoreComments() {
      if (this.comments.hasMore && this.commentsLoadMoreStatus !== 'loading') {
        this.comments.pageNum++
        this.loadComments(true)
      }
    }
  },
  onReachBottom() {
    this.loadMoreComments()
  }
}
</script>

<style lang="scss" scoped>
.detail-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 120rpx;
}

.product-swiper {
  width: 100%;
  height: 750rpx;
  background: #fff;
  
  image {
    width: 100%;
    height: 100%;
  }
}

.float-buttons {
  position: fixed;
  top: 60rpx;
  left: 30rpx;
  z-index: 100;
  display: flex;
  gap: 20rpx;
  
  .float-btn {
    width: 72rpx;
    height: 72rpx;
    border-radius: 50%;
    background: rgba(0, 0, 0, 0.5);
    backdrop-filter: blur(10px);
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s;
    
    &:active {
      transform: scale(0.95);
    }
  }
}

.product-info {
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .price-section {
    display: flex;
    align-items: baseline;
    margin-bottom: 20rpx;
    
    .price {
      font-size: 48rpx;
      color: $uni-primary;
      font-weight: bold;
      
      &::before {
        content: '¥';
        font-size: 32rpx;
        margin-right: 4rpx;
      }
    }
    
    .original-price {
      font-size: 28rpx;
      color: #999;
      text-decoration: line-through;
      margin-left: 20rpx;
      
      &::before {
        content: '¥';
        font-size: 24rpx;
      }
    }
  }
  
  .title-section {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 20rpx;
    
    .title {
      flex: 1;
      font-size: 32rpx;
      color: #333;
      font-weight: 500;
      line-height: 1.5;
      margin-right: 20rpx;
    }
    
    .share-btn {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 0 10rpx;
      
      text {
        font-size: 24rpx;
        color: #666;
        margin-top: 4rpx;
      }
    }
  }
  
  .desc {
    font-size: 28rpx;
    color: #666;
    line-height: 1.6;
    margin-bottom: 20rpx;
  }
  
  .sales-info {
    display: flex;
    gap: 40rpx;
    font-size: 24rpx;
    color: #999;
  }
}

.specs-section {
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .label {
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
  }
  
  .content {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    
    text {
      font-size: 28rpx;
      color: #666;
      margin-right: 10rpx;
      
      &.spec-placeholder {
        color: #999;
      }
    }
  }
}

.detail-section {
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .section-title {
    font-size: 32rpx;
    color: #333;
    font-weight: 500;
    margin-bottom: 20rpx;
    padding-left: 20rpx;
    border-left: 6rpx solid $uni-primary;
  }
}

.comments-section {
  background: #fff;
  padding: 30rpx;
  
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    padding-bottom: 20rpx;
    border-bottom: 2rpx solid #f5f5f5;
    
    .title {
      display: flex;
      align-items: baseline;
      
      .main {
        font-size: 32rpx;
        color: #333;
        font-weight: 500;
      }
      
      .count {
        font-size: 24rpx;
        color: #999;
        margin-left: 10rpx;
      }
    }
    
    .stats {
      display: flex;
      align-items: center;
      gap: 20rpx;
      
      .filter-btn {
        font-size: 24rpx;
        color: #666;
        display: flex;
        align-items: center;
        
        .uni-icons {
          margin-left: 4rpx;
        }
      }
    }
  }
  
  .comment-list {
    .comment-item {
      padding: 30rpx 0;
      border-bottom: 2rpx solid #f5f5f5;
      
      &:last-child {
        border-bottom: none;
      }
      
      .user-info {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 16rpx;
        
        .left {
          display: flex;
          align-items: center;
          
          .avatar {
            width: 64rpx;
            height: 64rpx;
            border-radius: 50%;
            margin-right: 16rpx;
            background-color: #f5f5f5;
          }
          
          .user-meta {
            .nickname {
              font-size: 28rpx;
              color: #333;
              margin-right: 20rpx;
            }
            
            .purchase-info {
              font-size: 24rpx;
              color: #ff5500;
              background-color: #fff5f0;
              padding: 4rpx 12rpx;
              border-radius: 4rpx;
              margin-top: 8rpx;
            }
          }
        }
        
        .time {
          font-size: 24rpx;
          color: #999;
        }
      }
      
      .rating {
        margin-bottom: 16rpx;
        display: flex;
        align-items: center;
      }
      
      .comment-content {
        font-size: 28rpx;
        color: #333;
        line-height: 1.6;
        margin-bottom: 20rpx;
      }
      
      .comment-images {
        display: flex;
        flex-wrap: wrap;
        gap: 12rpx;
        margin: 20rpx 0;
        
        image {
          width: 200rpx;
          height: 200rpx;
          border-radius: 12rpx;
          background-color: #f5f5f5;
          object-fit: cover;
        }
      }
      
      .comment-footer {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        margin-top: 20rpx;
        
        .actions {
          display: flex;
          gap: 30rpx;
          
          .action-btn {
            display: flex;
            align-items: center;
            gap: 8rpx;
            padding: 8rpx 16rpx;
            
            text {
              font-size: 24rpx;
              color: #999;
            }
          }
        }
      }
    }
  }
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background: #fff;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .left-btns {
    display: flex;
    gap: 40rpx;
    
    .btn-item {
      position: relative;
      display: flex;
      flex-direction: column;
      align-items: center;
      
      text {
        font-size: 20rpx;
        color: #666;
        margin-top: 4rpx;
      }
      
      .cart-badge {
        position: absolute;
        top: -10rpx;
        right: -16rpx;
        min-width: 32rpx;
        height: 32rpx;
        border-radius: 16rpx;
        background: $uni-primary;
        color: #fff;
        font-size: 20rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0 6rpx;
      }
    }
  }
  
  .right-btns {
    flex: 1;
    display: flex;
    justify-content: flex-end;
    gap: 20rpx;
    
    button {
      min-width: 180rpx;
      height: 72rpx;
      border-radius: 36rpx;
      font-size: 28rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      
      &.add-cart-btn {
        background: #fff;
        color: $uni-primary;
        border: 2rpx solid $uni-primary;
      }
      
      &.buy-btn {
        background: $uni-primary;
        color: #fff;
      }
      
      &:active {
        transform: scale(0.98);
      }
    }
  }
}

.specs-popup {
  background: #fff;
  border-radius: 24rpx 24rpx 0 0;
  max-height: 80vh;
  
  .popup-header {
    display: flex;
    padding: 30rpx;
    border-bottom: 2rpx solid #f5f5f5;
    position: relative;
    
    .product-image {
      width: 160rpx;
      height: 160rpx;
      border-radius: 12rpx;
      margin-right: 20rpx;
    }
    
    .selected-info {
      flex: 1;
      
      .price {
        font-size: 36rpx;
        color: $uni-primary;
        font-weight: bold;
        margin-bottom: 10rpx;
        
        &::before {
          content: '¥';
          font-size: 28rpx;
        }
      }
      
      .stock, .selected {
        display: block;
        font-size: 24rpx;
        color: #666;
        margin-top: 8rpx;
      }
    }
    
    .close-btn {
      position: absolute;
      top: 20rpx;
      right: 20rpx;
      padding: 10rpx;
    }
  }
  
  .specs-content {
    max-height: 60vh;
    padding: 30rpx;
    
    .spec-group {
      margin-bottom: 30rpx;
      
      .spec-title {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 20rpx;
      }
      
      .spec-items {
        display: flex;
        flex-wrap: wrap;
        gap: 20rpx;
        
        .spec-item {
          padding: 12rpx 30rpx;
          border-radius: 30rpx;
          font-size: 26rpx;
          color: #666;
          background: #f5f5f5;
          transition: all 0.3s;
          
          &.active {
            background: $uni-primary;
            color: #fff;
          }
          
          &:active {
            transform: scale(0.95);
          }
        }
      }
    }
  }
}

.empty-comments {
  text-align: center;
  padding: 60rpx 0;
  color: #999;
  font-size: 28rpx;
}

.comment-detail-popup {
  background: #fff;
  border-radius: 24rpx;
  width: 80vw;
  max-height: 80vh;
  
  .popup-header {
    padding: 30rpx;
    border-bottom: 2rpx solid #f5f5f5;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .title {
      font-size: 32rpx;
      color: #333;
      font-weight: 500;
    }
  }
  
  .popup-content {
    max-height: 60vh;
    padding: 30rpx;
  }
  
  .popup-footer {
    padding: 20rpx 30rpx;
    border-top: 2rpx solid #f5f5f5;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 